package site.brood.common.security.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import site.brood.common.core.context.SecurityContextHolder;
import site.brood.common.core.spring.SpringUtil;
import site.brood.common.core.str.StrUtil;
import site.brood.common.core.web.ServletUtil;
import site.brood.common.core.constant.Constants;
import site.brood.common.core.user.LoginUserVO;
import site.brood.common.security.service.TokenService;
import site.brood.common.security.util.SecurityUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义请求头拦截器，将Header数据封装到线程变量中方便获取
 * 注意：此拦截器会同时验证当前用户有效期自动刷新有效期
 */
public class HeaderInterceptor implements AsyncHandlerInterceptor
{

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
    {
        if (!(handler instanceof HandlerMethod))
        {
            return true;
        }

        TokenService tokenService = SpringUtil.getBean(TokenService.class);

        //从请求头中取出userId、username、userkey
        SecurityContextHolder.setUserId(ServletUtil.getHeader(request, Constants.THREAD_USER_ID));
        SecurityContextHolder.setUsername(ServletUtil.getHeader(request, Constants.THREAD_USER_NAME));
        SecurityContextHolder.setUserKey(ServletUtil.getHeader(request, Constants.THREAD_USER_CACHE_KEY));

        String token = SecurityUtil.getToken();
        if (StrUtil.isNotEmpty(token))
        {
            LoginUserVO loginUserVO = tokenService.getLoginUser(token);
            if (StrUtil.isNotNull(loginUserVO))
            {
                //将登录令牌在reids中的过期时间延长720分钟
                tokenService.verifyToken(loginUserVO);
                //将用户详情存入TransmittableThreadLocal
                SecurityContextHolder.set(Constants.THREAD_USER, loginUserVO);
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception
    {
        SecurityContextHolder.remove();
    }
}
